//
//  EFADeviceInfoVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/7/13.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFADeviceInfoVC.h"
#import "EFADevInfoTCell.h"
#import "EFADevInfoChartTCell.h"
#import "EFADevInfoImgTCell.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "EFAModel.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "EFAMsgControlCVC.h"
#import "EFAMaintenanceVC.h"
#import "KSPhotoBrowser.h"

@interface EFADeviceInfoVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource, EFADevInfoImgTCellDelegate>
@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (weak,   nonatomic) IBOutlet UIButton *phoneBtn;
@property (strong, nonatomic) UIBarButtonItem *controlBarBtnItem;
@property (strong, nonatomic) UIBarButtonItem *maintenanceBarBtnItem;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
//@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer

@property (strong, nonatomic) EFADeviceInfoModel *deviceInfo;
@end

static NSString *const kReuseTitleCellId = @"EFADevInfoTCell";
static NSString *const kReuseChartCellId = @"EFADevInfoChartTCell";
static NSString *const kReuseImgCellId = @"EFADevInfoImgTCell";
//static NSInteger const kRequestUserSize = 20;

@implementation EFADeviceInfoVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = @"设备信息";
    self.navigationItem.rightBarButtonItems = @[self.controlBarBtnItem, self.maintenanceBarBtnItem];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    [self.phoneBtn addTarget:self action:@selector(phoneBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    UINib *titleNib = [UINib nibWithNibName:kReuseTitleCellId bundle:nil];
    [self.tableView registerNib:titleNib forCellReuseIdentifier:kReuseTitleCellId];
    UINib *chartNib = [UINib nibWithNibName:kReuseChartCellId bundle:nil];
    [self.tableView registerNib:chartNib forCellReuseIdentifier:kReuseChartCellId];
    UINib *imgNib = [UINib nibWithNibName:kReuseImgCellId bundle:nil];
    [self.tableView registerNib:imgNib forCellReuseIdentifier:kReuseImgCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 252.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    
    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
    //    self.tableView.mj_footer = self.mj_footer;
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"当前没有信息" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    //    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
    return nil;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        if (self.deviceInfo) {
            return 10 + (self.deviceInfo.realtime_data.filterData.count ? self.deviceInfo.realtime_data.filterData.count + 3 : 0);
        }
        return 0;
    } else if (section == 1) {
        return self.deviceInfo.streamPtCidArray.count; // 一种参量类型是一个表格
    }
    
    return self.deviceInfo.device_info.efairydevice_imgurl_list.count ? 1 : 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        EFADevInfoTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseTitleCellId forIndexPath:indexPath];
        [cell configViewWithEFADeviceInfoModel:self.deviceInfo indexPath:indexPath];
        return cell;
    } else if (indexPath.section == 1) {
        EFADevInfoChartTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseChartCellId forIndexPath:indexPath];
        [cell configViewWithEFADeviceInfoModel:self.deviceInfo indexPath:indexPath];
        return cell;
    }
    
    EFADevInfoImgTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseImgCellId forIndexPath:indexPath];
    [cell configViewWithDevInfoModel:self.deviceInfo];
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.9;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - EFADevInfoImgTCellDelegate
- (void)devInfoImgTCell:(EFADevInfoImgTCell *)cell imgViewTapped:(NSArray<UIImageView *> *)imgViewArray indexPath:(NSIndexPath *)cIndexPath {
    if (cIndexPath.row >= self.deviceInfo.device_info.efairydevice_imgurl_list.count) {
        return;
    }
    
    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:self.deviceInfo.device_info.efairydevice_imgurl_list.count];
    [self.deviceInfo.device_info.efairydevice_imgurl_list enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIImageView *tempImgView = nil;
        if (idx < imgViewArray.count) {
            tempImgView = imgViewArray[idx];
        }
        KSPhotoItem *photoItem = [KSPhotoItem itemWithSourceView:tempImgView imageUrl:[NSURL URLWithString:obj]];
        [mArray addObject:photoItem];
    }];
    [self showPhotoBrowser:mArray selectedIndex:cIndexPath.row];
}

#pragma mark - event response
- (void)phoneBtnTapped:(UIButton *)btn {
    if ((!self.deviceInfo.device_info.efairyproject_user_info_list.count)
        && (!self.deviceInfo.device_info.efairydevice_user_info_list.count)) {
        return;
    }
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    NSArray<EFADevPjtUserInfo *> *dataArray = self.deviceInfo.device_info.efairyproject_user_info_list;
    __weak typeof(self) weakSelf = self;
    for (EFADevPjtUserInfo *userInfo in dataArray) {
        NSString *title = [NSString stringWithFormat:@"%@ %@", userInfo.efairyuser_nickname, userInfo.efairyuser_phonenumber];
        [alertVC addAction:[UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf callSomeOneWithPhoneNum:userInfo.efairyuser_phonenumber];
        }]];
    }
    dataArray = self.deviceInfo.device_info.efairydevice_user_info_list;
    for (EFADevPjtUserInfo *userInfo in dataArray) {
        NSString *title = [NSString stringWithFormat:@"%@ %@", userInfo.efairyuser_nickname, userInfo.efairyuser_phonenumber];
        [alertVC addAction:[UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf callSomeOneWithPhoneNum:userInfo.efairyuser_phonenumber];
        }]];
    }
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)maintenanceBarBtnItemTapped:(UIBarButtonItem *)item {
    EFAMaintenanceVC *vc = [[EFAMaintenanceVC alloc] init];
    vc.device_id = self.deviceId;
    [self showViewController:vc sender:nil];
}
- (void)controlBarBtnItemTapped:(UIBarButtonItem *)item {
    if (self.isFromControl) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
    UIStoryboard *mainSb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    EFAMsgControlCVC *vc = [mainSb instantiateViewControllerWithIdentifier:@"EFAMsgControlCVC"];
    vc.device_id = self.deviceId;
    vc.device_name = self.device_name;
    vc.isFromDeviceInfo = YES;
    [self showViewController:vc sender:nil];
}
#pragma mark - private methods
- (void)showPhotoBrowser:(NSArray<KSPhotoItem *> *)photoItems selectedIndex:(NSUInteger)index {
    KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:photoItems selectedIndex:index];
    browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleNone;
    browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlack;
    browser.loadingStyle = KSPhotoBrowserImageLoadingStyleDeterminate;
    browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleDot;
    browser.bounces = NO;
    [browser showFromViewController:self];
}

- (void)callSomeOneWithPhoneNum:(NSString *)num {
    NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", num];
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
    }
}

- (void)refreshWholeView {
    //    // 尾部加载更多的显示
    //    if (self.userList.totalLoad) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    BOOL phoneHidden = ((!self.deviceInfo.device_info.efairyproject_user_info_list.count)
    && (!self.deviceInfo.device_info.efairydevice_user_info_list.count));
    self.phoneBtn.hidden = phoneHidden;
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestDeviceInfoWithHeader:isHeader];
}
#pragma mark - network request
- (void)requestDeviceInfoWithHeader:(BOOL)isHeader {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        [self tableViewEndRefresh:isHeader];
        return;
    }
    
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairydevice_id" : @(self.deviceId),
//                           @"start_time" : @"2017-07-25",D
                           @"days" : @(1)
                           };
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiDeviceOld] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求设备信息返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        self.deviceInfo = [EFADeviceInfoModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        [self.deviceInfo unzipStreamList];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求设备信息失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (UIBarButtonItem *)maintenanceBarBtnItem {
    if (!_maintenanceBarBtnItem) {
        _maintenanceBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"device_maintenance"] style:UIBarButtonItemStylePlain target:self action:@selector(maintenanceBarBtnItemTapped:)];
    }
    return _maintenanceBarBtnItem;
}
- (UIBarButtonItem *)controlBarBtnItem {
    if (!_controlBarBtnItem) {
        _controlBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"device_control"] style:UIBarButtonItemStylePlain target:self action:@selector(controlBarBtnItemTapped:)];
    }
    return _controlBarBtnItem;
}
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}
@end
